import { CdkDropList, CdkDrag } from '@angular/cdk/drag-drop';
import { NgClass, NgStyle } from '@angular/common';
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AntTableComponent, AntTableConfig } from '@app/shared/components/ant-table/ant-table.component';
import { DraggableDirective } from '@app/shared/directives/draggable.directive';
import { DroppableDirective } from '@app/shared/directives/droppable.directive';
import { ResizableModule } from 'angular-resizable-element';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzTableModule } from 'ng-zorro-antd/table';

import { DashboardWidget } from '../dashboard-widget';
import { CustomColumn, WidgetConfig } from '../widget-default-setting';
import { WidgetSharedService } from '../widgetShared.service';

@Component({
  selector: 'app-table-widget',
  standalone: true,
  imports: [AntTableComponent, DraggableDirective, DroppableDirective, CdkDropList, ResizableModule, NgStyle, CdkDrag, NgClass, NzTableModule, NgStyle, NzInputModule, FormsModule],
  templateUrl: './table-widget.component.html',
  styleUrl: './table-widget.component.less'
})
export class TableWidgetComponent extends DashboardWidget implements OnInit {
  @ViewChild('basicTable') basicTable!: ElementRef<HTMLElement>;
  @Input() currentWidget!: WidgetConfig;
  @Output() readonly resizeEvent = new EventEmitter();
  tableConfig!: AntTableConfig;
  dataList: NzSafeAny[] = [];
  constructor(private readonly sharedService: WidgetSharedService) {
    super();
    this.resizeWidgetEvent = this.resizeEvent;
  }

  override getWidget(): WidgetConfig | null {
    return this.currentWidget;
  }

  get dataSourceList(): NzSafeAny[] {
    return this.widget!['tableConfig'].dataSourceList;
  }

  get customColumn(): CustomColumn[] {
    return this.widget!['tableConfig'].customColumn.filter((r: NzSafeAny) => r.name != '操作');
  }

  initTableConfig(): void {
    if (this.widget) {
      this.widget['tableConfig'] = {
        dataSourceList: [{ id: 0, title: 'daemon', desc: '让页面制作更简单' }],
        customColumn: [
          {
            name: '标题',
            value: 'title',
            default: true,
            required: false,
            position: 'left',
            width: 200,
            fixWidth: true
          },
          {
            name: '描述',
            value: 'desc',
            default: true,
            width: 200
          }
        ]
      };
    }
  }

  getDataList(): void {
    return this.widget!['tableConfig']?.dataSourceList;
  }

  // set the style of inner table. we only do it like this at present.  TODO: make code better.
  setInnerTableStyle(): void {
    const innerTable = this.basicTable.nativeElement.querySelector('.ant-table-container') as HTMLElement;
    // droppable container
    const droppableContainer = document.querySelector('.right-design');
    const pagination = this.basicTable.nativeElement.querySelector('.ant-pagination');
    if (this.widget!.layout) {
      innerTable!.style.width = `${Math.round((parseFloat(this.widget!.layout.width.replace('%', '')) * droppableContainer!.clientWidth) / 100) - 6}px`;
      // 16 is margin value
      innerTable!.style.height = `${Math.round((parseFloat(this.widget!.layout.height.replace('%', '')) * droppableContainer!.clientHeight) / 100) - pagination!.clientHeight - 22}px`;
      innerTable!.style.overflowY = 'auto';
    }
  }

  ngOnInit(): void {
    this.sharedService.initWidget.subscribe((widget: WidgetConfig | null) => {
      if (!this.currentWidget) {
        this.currentWidget = widget!;
        this.setInnerTableStyle();
      }
    });

    this.sharedService.updateWidget.subscribe((widget: WidgetConfig | null) => {
      if (widget?.tag === this.currentWidget.tag) {
        this.currentWidget = widget!;
        this.setInnerTableStyle();
      }
    });

    this.initTableConfig();
  }
}
